/**
 * @System hgs
 * @Description: Copyright: Copyright (c) 2018
 * Company: Aspire Technologies
 * @Author raoyuxing
 * @Date 2018/10/25 17:17
 * @version V1.0
 */
package com.fire.user.util.auth;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.lang3.StringUtils;
import com.alibaba.fastjson.JSONObject;


/**
 * @ClassName: UniapiTokenValidateDemo
 * @Description: TODO
 * @Author raoyuxing
 * @Date 2018/10/25 17:17 
 */
public class UniapiTokenValidateDemo {

    static String tokenValidateUrl = "http://112.13.96.207:10080/test/api/uniTokenValidate";

    public static void main(String[] args) throws HttpException, IOException {
        //生成新的请求报文
        String createSign = UniapiTokenValidateDemo.createSign("3", "100000", "0", "123456789", "5dc3722e-9520-4769-8bb4-07d20ee4091d", "20180928104639465", "8484010001320200344E6A5A4551554D784F444E474E446C434E446779517A673340687474703A2F2F3139322E3136382E31322E3233363A393039302F0300040353EA68040006313030303030FF00203A020A143C6703D7D0530953C760744C7D61F5F7B546F12BC17D65254878748C", "1.0");
        String response = postMethod(createSign);
        System.out.println(response);
    }


    /**
     *
     * 将传入的参数自动变成报文
     *
     * @Title: 请求排序key不为null
     * @param appid,id,idtype,key,msgid,systemtime,token,version
     * @return requestJson
     * @author:wei
     */
    private static JSONObject requestSort(String apptype,String id,String idtype,String key,String msgid,String systemtime,String token,String version) {
        JSONObject requestJson = new JSONObject();
        JSONObject header = new JSONObject();
        JSONObject body = new JSONObject();
        body.put("token", token);
        header.put("msgid", msgid);
        header.put("systemtime", systemtime);
        header.put("version", version);
        header.put("id", id);
        header.put("apptype",apptype);
        header.put("idtype", idtype);
        header.put("key", key);
        requestJson.put("header", header);
        requestJson.put("body", body);
        return requestJson;
    }

    /**
     *
     * 将传入的参数自动变成报文
     *
     * @Title: 请求排序key为null
     * @param appid,id,idtype,msgid,systemtime,token,version
     * @return requestJson
     * @author:wei
     */
    private static JSONObject requestSort(String apptype,String id,String idtype,String msgid,String systemtime,String token,String version) {
        JSONObject requestJson = new JSONObject();
        JSONObject header = new JSONObject();
        JSONObject body = new JSONObject();
        body.put("token", token);
        header.put("msgid", msgid);
        header.put("systemtime", systemtime);
        header.put("version", version);
        header.put("id", id);
        header.put("apptype",apptype);
        header.put("idtype", idtype);
        requestJson.put("header", header);
        requestJson.put("body", body);
        return requestJson;
    }

    /**
     *
     * 发送post请求；
     *
     * @Title: 发送post请求
     * @param requestJson
     * @return responseJson
     * @author:wei
     */
    private static String postMethod(String reauestJson)
            throws UnsupportedEncodingException, IOException, HttpException {
        HttpClient client = new HttpClient();
        PostMethod postMethod1 = new PostMethod(tokenValidateUrl);
        RequestEntity entity = new StringRequestEntity(reauestJson, null, "utf-8");
        postMethod1.setRequestEntity(entity);
        client.executeMethod(postMethod1);
        String resp1 = postMethod1.getResponseBodyAsString();
        //System.out.println(resp1);
        return resp1;
    }
    /**
     *
     * 将传入的参数自动变成报文
     *
     * @Title: 创建签名
     * @param appid,id,idtype,key,msgid,systemtime,token,version
     * @return requestJson
     * @author:wei
     */
    public static String createSign(String appid,String id,String idtype,String key,String msgid,String systemtime,String token,String version){

        JSONObject requestSort = requestSort( appid, id, idtype, key, msgid, systemtime, token, version);
        String reauestJson = createSign(requestSort.toJSONString());
        return reauestJson;
    }

    /**
     *
     * 将传入的参数自动变成报文
     *
     * @Title: 创建签名 key 为null
     * @param appid,id,idtype,msgid,systemtime,token,version
     * @return
     * @author:wei
     */
    public static String createSign(String appid,String id,String idtype,String msgid,String systemtime,String token,String version){

        JSONObject requestSort = requestSort( appid, id, idtype,  msgid, systemtime, token, version);
        String reauestJson = createSign(requestSort.toJSONString());
        return reauestJson;
    }

    /**
     *
     * 将传入的参数自动变成报文
     *
     * @Title: 创建签名
     * @param JsonString
     * @return
     * @author:
     */
    public static String createSign(String JsonString){
        JSONObject json = JSONObject.parseObject(JsonString);
        String sign ="";

        if (json == null) {
            throw new IllegalArgumentException("请求数据不能为空");
        }
        JSONObject respheader = json.getJSONObject("header");
        JSONObject respbody = json.getJSONObject("body");
        if (respheader == null) {
            throw new IllegalArgumentException("请header不能为空");
        }
        if (respbody == null) {
            throw new IllegalArgumentException("请body不能为空");
        }
        String apptype =(String)respheader.get("apptype");
        String id =(String)respheader.get("id");
        String idtype =(String)respheader.get("idtype");
        String key =(String)respheader.get("key");
        String msgid =(String)respheader.get("msgid");
        String systemtime =(String)respheader.get("systemtime");
        String version =(String)respheader.get("version");
        String token =(String)respbody.get("token");
        if(StringUtils.isBlank(apptype)){
            throw new IllegalArgumentException("apptype不能为空");
        }
        if(StringUtils.isBlank(id)){
            throw new IllegalArgumentException("id不能为空");
        }
        if(StringUtils.isBlank(idtype)){
            throw new IllegalArgumentException("idtype不能为空");
        }
        if(StringUtils.isBlank(msgid)){
            throw new IllegalArgumentException("msgid不能为空");
        }
        if(StringUtils.isBlank(systemtime)){
            throw new IllegalArgumentException("systemtime不能为空");
        }
        if(StringUtils.isBlank(version)){
            throw new IllegalArgumentException("version不能为空");
        }
        if(StringUtils.isBlank(token)){
            throw new IllegalArgumentException("token不能为空");
        }
        Map<String, Object> map = new TreeMap<String, Object>();
        map.put("version", version);
        map.put("id", id);
        map.put("idtype", idtype);
        map.put("msgid", msgid);
        map.put("token", token);
        map.put("systemtime", systemtime);
        map.put("apptype", apptype);
        if(StringUtils.isBlank(key)){
            String enStr = mapToString(map);
            sign = md5(enStr);
        }else{
            map.put("key", key);
            String enStr = mapToString(map);
            sign = md5(enStr);
        }
        json.getJSONObject("header").put("sign", sign);
        json.getJSONObject("header").remove("key");
        return json.toJSONString();
    }

    /**
     *
     * 将Map转换为String
     *
     * @Title: map2String
     * @param map
     * @return
     * @author: yanhuajian 2013-7-21下午7:25:08
     */
    private static String mapToString(Map<String, Object> map) {
        if (null == map || map.isEmpty()) {
            return null;
        }

        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            sb.append(entry.getValue());
        }

        return sb.toString();
    }

    private static String md5(String text) {
        String result = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(text.getBytes("UTF-8"));
            byte[] b = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0) {
                    i += 256;
                }
                if (i < 16) {
                    buf.append("0");
                }
                buf.append(Integer.toHexString(i));
            }
            result = buf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
